var formidable = require('formidable');
var util = require('util');
var fs = require('fs');

function upload(request, response) {

    if(request.method.toLowerCase() == 'post') {
        
        var form = new formidable.IncomingForm();
        
        form.uploadDir = './tmp';

        form.parse(request, function(err, fields, files) {
            var oldname = files.upload.name;
            var newname = Date.now() + oldname.substr(oldname.lastIndexOf('.'));
            fs.renameSync(files.upload.path, './img/' + newname);

            response.writeHead(200, {'content-type': 'text/html'});

            var s = '\
                <p>\
                    <a href="/" rel="external nofollow">back</a>\
                </p>\
                <p>\
                    <img src="/showimg?src='+newname+'" />\
                </p>\
            \n';

            response.write('received upload.\n');
            response.write(s);
            response.end(util.inspect({fields: fields, files: files}));
        });

        return;

    }

}

exports.upload = upload;